
/**
 * 队列 FIFO 先来先服务
 */
export class Queue<T>{

    private _count: number;
    private _lowestCount: number;
    private _items: any;

    public constructor() {
        this._count = this._lowestCount = 0;
        this._items = {};
    }

    /**
     * 向队列尾部添加一个新的项
     * @param element 
     */
    public enqueue(element: T) {
        this._items[this._count] = element;
        this._count++;
    }

    /**
     * 移除队列的第一项
     */
    public dequeue() {
        if (this.isEmpty()) {
            return undefined;
        }
        const result = this._items[this._lowestCount];
        delete this._items[this._lowestCount];
        this._lowestCount++;
        return result;
    }

    /**
     * 返回队列中第一个元素
     */
    public peek() {
        if (this.isEmpty()) {
            return undefined;
        }
        return this._items[this._lowestCount];
    }

    /**
     * 判断队列是否为空
     */
    public isEmpty() {
        return this._count - this._lowestCount === 0;
    }

    /**
     * 返回队列包含的元素个数
     */
    public get length() {
        return this._count - this._lowestCount;
    }

    /**
     * 清空队列
     */
    public clear() {
        this._items = {};
        this._count = 0;
        this._lowestCount = 0;
    }

    public toString() {
        if (this.isEmpty()) {
            return '';
        }
        let objStr = `${this._items[this._lowestCount]}`;
        for (let i = this._lowestCount + 1; i < this._count; i++) {
            objStr = `${objStr},${this._items[i]}`;
        }
        return objStr;
    }
}